package xin.codedream.codelog.web.controller.admin;

import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import xin.codedream.codelog.model.entity.Logs;
import xin.codedream.codelog.model.enums.PageInfoEnum;
import xin.codedream.codelog.service.LogsService;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * 日志信息控制器
 *
 * @author NGLSL
 * @date 2018/8/5
 */
@Slf4j
@RestController
@RequestMapping("/admin/logs")
public class LogsController {
    @Resource
    private LogsService logsService;

    /**
     * 获取所有日志信息
     *
     * @param startTime 开始日期
     * @param endTime   结束日期
     * @param pageNum   当前页
     * @param pageSize  每页的数量
     * @return ModelAndView 响应数据
     */
    @RequestMapping("/showLogs")
    public ModelAndView showAllLogs(String startTime, String endTime,
                                    Integer pageNum, Integer pageSize) {
        ModelAndView mv = new ModelAndView("admin/admin_logs");
        if (Objects.isNull(pageNum) || Objects.isNull(pageSize)) {
            pageSize = PageInfoEnum.PAGE_DEFAULT_NUM.getValue();
            pageNum = PageInfoEnum.PAGE_DEFAULT_SIZE.getValue();
        }
        List<Logs> logs = logsService.findAllLogs(pageNum, pageSize, startTime, endTime);
        PageInfo<Logs> pageInfo = new PageInfo<>(logs);
        mv.addObject("pageInfo", pageInfo);
        mv.addObject("pageNum", pageNum);
        mv.addObject("pageSize", pageSize);
        mv.addObject("logs", logs);
        mv.addObject("startTime", startTime);
        mv.addObject("endTime", endTime);
        return mv;
    }

    /**
     * 清空所有日志
     *
     * @return String
     */
    @GetMapping("/removeAllLog")
    public ModelAndView removeAllLog() {
        boolean result = logsService.removeAllLog();
        log.info("清空所有日志结果：{}", result);
        return new ModelAndView("redirect:/admin/logs/showLogs");
    }
}
